var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');
var InfiniteLoop = require('infinite-loop');

var il = new InfiniteLoop();
il.add(test).run();
function test(){
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:27017/amobi', function(err, db) {
//	while(true){
// Establish connection to db
  // Create a collection we want to drop later
//  db.createCollection('simple_find_and_modify_operations_', function(err, collection) {
//    assert.equal(null, err);
	var collection = db.collection('simple_find_and_modify_operations_');
//       Simple findAndModify command returning the new document
      collection.findAndModify({f1:1}, [['a', 1]], {$set:{}}, {new:true, upsert:true, w:1}, function(err, doc) {
    	  console.log(doc.clicks);
    	  if(typeof doc.clicks=="undefined"){
    		  doc.clicks=1;
    		  collection.findAndModify({f1:1},[['a', 1]],{$set:{clicks:1}},{new:true, upsert:true, w:1},function(err,doc){
    			  console.log(doc);
//    		      db.close();
    		  });

    	  }else{
    		  collection.findAndModify({f1:1},[['a', 1]],{$set:{clicks:doc.clicks+1}},{new:true, upsert:true, w:1},function(err,doc){
    			  console.log(doc);
//    		      db.close();
    		  });

    	  }
    	  console.log(doc.clicks);
      });
//  });
//      db.close();
//	}
});
}